#!/bin/bash

# Git Push Script - Automatically detects remote and pushes all changes
# Usage: ./gitpush.sh [commit_message]

set -e  # Exit on any error

# Make git operations non-interactive
export GIT_TERMINAL_PROMPT=0
export GIT_ASKPASS=true
export GIT_PAGER=cat  # Disable pager to prevent interactive prompts

# Default commit message
DEFAULT_MESSAGE="Update files $(date '+%Y-%m-%d %H:%M:%S')"
COMMIT_MESSAGE="${1:-$DEFAULT_MESSAGE}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== Git Push Script ===${NC}"

# Check if we're in a git repository
if ! git rev-parse --git-dir > /dev/null 2>&1; then
    echo -e "${RED}Error: Not in a git repository${NC}"
    exit 1
fi

# Get the current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ -z "$CURRENT_BRANCH" ]]; then
    echo -e "${RED}Error: Could not determine current branch${NC}"
    exit 1
fi
echo -e "${BLUE}Current branch: ${YELLOW}$CURRENT_BRANCH${NC}"

# Auto-detect remote name
echo -e "${BLUE}Detecting git remote...${NC}"
REMOTES=$(git remote)

if [[ -z "$REMOTES" ]]; then
    echo -e "${RED}Error: No git remotes found${NC}"
    exit 1
fi

# First, try to use the upstream remote configured for the current branch
REMOTE_NAME=""
UPSTREAM_REMOTE=""

# Get the upstream remote if configured
UPSTREAM_REF=$(git symbolic-ref -q HEAD 2>/dev/null || echo "")
if [[ -n "$UPSTREAM_REF" ]]; then
    UPSTREAM_BRANCH=$(git for-each-ref --format='%(upstream:short)' "$UPSTREAM_REF" 2>/dev/null || echo "")
    if [[ -n "$UPSTREAM_BRANCH" ]]; then
        UPSTREAM_REMOTE=$(echo "$UPSTREAM_BRANCH" | cut -d'/' -f1)
        echo -e "${BLUE}Found upstream remote: ${YELLOW}$UPSTREAM_REMOTE${NC} (tracking $UPSTREAM_BRANCH)"
    fi
fi

# Use upstream remote if it exists and is valid
if [[ -n "$UPSTREAM_REMOTE" ]] && echo "$REMOTES" | grep -q "^$UPSTREAM_REMOTE$"; then
    REMOTE_NAME="$UPSTREAM_REMOTE"
    echo -e "${BLUE}Using upstream remote: ${YELLOW}$REMOTE_NAME${NC}"
else
    # Fallback to preference order: 'origin', then 'local', then first one
    if echo "$REMOTES" | grep -q "^origin$"; then
        REMOTE_NAME="origin"
        echo -e "${BLUE}Using fallback remote: ${YELLOW}$REMOTE_NAME${NC}"
    elif echo "$REMOTES" | grep -q "^local$"; then
        REMOTE_NAME="local"
        echo -e "${BLUE}Using fallback remote: ${YELLOW}$REMOTE_NAME${NC}"
    else
        REMOTE_NAME=$(echo "$REMOTES" | head -n1)
        echo -e "${BLUE}Using fallback remote: ${YELLOW}$REMOTE_NAME${NC}"
    fi
fi

# Show remote URL
REMOTE_URL=$(git config --get remote."$REMOTE_NAME".url)
echo -e "${BLUE}Remote URL: ${YELLOW}$REMOTE_URL${NC}"

# Check for both unstaged changes and untracked files
HAS_UNSTAGED_CHANGES=false
HAS_UNTRACKED_FILES=false

# Check for unstaged changes in tracked files
if ! git diff-index --quiet HEAD --; then
    HAS_UNSTAGED_CHANGES=true
fi

# Check for untracked files (excluding those in .gitignore)
if [[ -n $(git ls-files --others --exclude-standard) ]]; then
    HAS_UNTRACKED_FILES=true
fi

if $HAS_UNSTAGED_CHANGES || $HAS_UNTRACKED_FILES; then
    if $HAS_UNSTAGED_CHANGES; then
        echo -e "${YELLOW}Found unstaged changes in tracked files${NC}"
    fi
    if $HAS_UNTRACKED_FILES; then
        echo -e "${YELLOW}Found untracked files${NC}"
    fi
    
    # Show status
    echo -e "${BLUE}Git status:${NC}"
    git --no-pager status --porcelain
    
    # Add all changes (respects .gitignore)
    echo -e "${BLUE}Adding all changes...${NC}"
    git add --all .
    
    # Show what will be committed
    echo -e "${BLUE}Changes to be committed:${NC}"
    git --no-pager diff --cached --name-status
    
    # Commit changes
    echo -e "${BLUE}Committing with message: ${YELLOW}'$COMMIT_MESSAGE'${NC}"
    git commit -m "$COMMIT_MESSAGE"
else
    echo -e "${YELLOW}No changes to commit${NC}"
fi

# Check if there are commits to push
if git --no-pager log "$REMOTE_NAME/$CURRENT_BRANCH..$CURRENT_BRANCH" --oneline 2>/dev/null | grep -q .; then
    echo -e "${BLUE}Pushing to $REMOTE_NAME/$CURRENT_BRANCH...${NC}"
    # Use --set-upstream to automatically set tracking and --quiet to reduce output
    git push --set-upstream "$REMOTE_NAME" "$CURRENT_BRANCH" --quiet
    echo -e "${GREEN}✓ Successfully pushed to $REMOTE_NAME/$CURRENT_BRANCH${NC}"
else
    echo -e "${YELLOW}No new commits to push${NC}"
fi

echo -e "${GREEN}=== Git push completed ===${NC}" 